<?php

namespace App\Console\Commands;

use App\Models\Qh_School;
use App\Models\Qh_SchoolPlan;
use App\Models\Qh_SchoolSpec;
use DB;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Log;
use Throwable;

class ImportSchools extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:school';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入学校';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return string
     * @throws Throwable
     */
    public function handle(): string
    {
        $doneCount = 0;
        $dir = storage_path('app/import/school');
        if (!is_dir($dir)) {
            echo '无效目录';
            return false;
        }
        $files = glob($dir . '/*');
        $allCount = count($files);
        foreach ($files as $file) {
            if (is_dir($file)) {
                continue;
            } else {
                $logs = [
                    'schoolId' => null,
                    'schoolName' => null,
                    'errors' => []
                ];

                try {
                    $jsonStr = fread(fopen($file, 'r'), filesize($file));
                    $json = json_decode($jsonStr);

                    $pattern = '/\d{4}/';
                    $createYear = preg_match($pattern, $json->info->create_time, $matches) ? $matches[0] : date("Y");

                    $tags = $json->info->mark4;
                    shuffle($tags);

                    $_school = [
                        'name' => $json->info->school,
                        'province' => $json->info->sheng,
                        'url' => count(array_filter(explode(',', $json->info->web))) > 0 ? array_filter(explode(',', $json->info->web))[0] : null,
                        //'thumb' => $json->info->school,
                        'logo' => $json->info->logo_local,
                        'city' => $json->info->address,
                        'address' => $json->info->address1,
                        'tel' => $json->info->tele,
                        'email' => $json->info->email,
                        'baoMingUrl' => $json->info->baoming,
                        'chengJiUrl' => $json->info->chengji,
                        'fenShuUrl' => $json->info->fenshu,
                        'area' => $json->info->area,
                        'jiaoYuTing' => $json->info->shuyu,
                        'detail' => $json->info->detail,
                        'createYear' => $createYear,
                        'tags' => !empty($tags) ? implode(',', $tags) : null,
                        // 'images' => !empty($json->imglist) ? implode(',', $json->imglist) : null,
                    ];
                    if (!empty($json->info->mark3)) {
                        $_school['type'] = $json->info->mark3; // 院校类型/类型
                    }else {
                        $logs['errors'][] = 'mark3（类型）缺失';
                    }
                    if (!empty($json->info->mark2)) {
                        $_school['level'] = $json->info->mark2; // 办学层次
                    }else {
                        $logs['errors'][] = 'mark2（办学层次）缺失';
                    }
                    if (!empty($json->info->mark1)) {
                        $_school['bxType'] = $json->info->mark1; // 办学类型
                    }else {
                        $logs['errors'][] = 'mark1（办学类型）缺失';
                    }

                    // 获取专业，去重
                    $_school['spec'] = [];
                    foreach ($json->info1 as $spec) {
                        $_school['spec'][] = [
                            'level1Name' => $spec->lei1,
                            'level2Name' => $spec->lei2,
                            'name' => $spec->lei3,
                            'class' => $spec->zycc,
                            // 'province' => $spec->sheng,
                            'code' => $spec->zydm,
                            'xz' => $spec->jbxz,
                        ];
                    }

                    // 获取招生计划（等所有的专业入库完成，当前学校入库完成再入库绑定）
                    $_school['plan'] = [];
                    foreach ($json->zhaoshengjihua as $p) {
                        $c = explode(',', $p->tiaojian);
                        $_school['plan'][] = [
                            'specName' => $p->name,
                            'class' => $c[4],
                            'year' => $c[0], // 年份
                            'num' => $p->num,
                            'whcd' => $c[3],
                            'xz' => $p->years,
                            'price' => is_numeric($p->price) ? $p->price : 0,
                            'c1' => $c[2],
                            'remarks' => $p->notes ?? null,
                        ];
                    }
                }catch (Exception $e) {
                    Log::debug('【'.$file.'】解析失败：原因：'.$e->getMessage());
                    echo '【'.$file.'】解析失败：原因：'.$e->getMessage().PHP_EOL;
                    continue;
                }

                // 入库
                // 查同名、同省份
                try {
                    DB::beginTransaction();
                    $school = Qh_School::where('name', $_school['name'])->first();
                    if ($school) {
                        // 省份
                        $province = is_array($school->province) ? $school->province : json_decode($school->province, JSON_UNESCAPED_UNICODE);
                        $province = is_array($province) ? $province : (is_null($province) ? [] : [$province]);
                        if (!in_array($_school['province'], $province)) {
                            $province[] = $_school['province'];
                            $school->province = json_encode($province, JSON_UNESCAPED_UNICODE);
                            $school->save();
                        }
                    }else {
                        $_school['province'] = json_encode([$_school['province']], JSON_UNESCAPED_UNICODE);
                        $school = Qh_School::create(Arr::except($_school, ['spec', 'plan']));

                        // 创建专业
                        $specIds = [];
                        foreach ($_school['spec'] as $_spec) {
                            $provinces = is_array($school->province) ? json_encode($school->province, JSON_UNESCAPED_UNICODE) : $school->province;
                            // 一级专业
                            $spec1 = Qh_SchoolSpec::where('name', $_spec['level1Name'])->where('level', 1)->first();
                            if (!$spec1) {
                                $spec1 = Qh_SchoolSpec::create([
                                    'parentId' => null,
                                    'level' => 1,
                                    'name' => $_spec['level1Name'],
                                    'class' => $_spec['class'],
                                    'province' => $provinces,
                                    'xz' => $_spec['xz']
                                ]);
                            }else {
                                // $s_provinces = json_decode($spec1->province, JSON_UNESCAPED_UNICODE);
                                $s_provinces = is_array($spec1->province) ? $spec1->province : (is_null($spec1->province) ? [] : json_decode($spec1->province, JSON_UNESCAPED_UNICODE));
                                $s_provinces = array_unique(array_merge(json_decode($provinces, JSON_UNESCAPED_UNICODE), $s_provinces));
                                $spec1->province = json_encode(array_values($s_provinces), JSON_UNESCAPED_UNICODE);
                                $spec1->save();
                            }

                            // 二级专业
                            $spec2 = Qh_SchoolSpec::where('name', $_spec['level2Name'])->where('level', 2)->first();
                            if (!$spec2) {
                                $spec2 = Qh_SchoolSpec::create([
                                    'parentId' => $spec1->id,
                                    'level' => 2,
                                    'name' => $_spec['level2Name'],
                                    'class' => $_spec['class'],
                                    'province' => $provinces,
                                    'xz' => $_spec['xz']
                                ]);
                            }else {
                                // $s_provinces = json_decode($spec2->province, JSON_UNESCAPED_UNICODE);
                                $s_provinces = is_array($spec2->province) ? $spec2->province : (is_null($spec2->province) ? [] : json_decode($spec2->province, JSON_UNESCAPED_UNICODE));
                                $s_provinces = array_unique(array_merge(json_decode($provinces, JSON_UNESCAPED_UNICODE), $s_provinces));
                                $spec2->province = json_encode(array_values($s_provinces), JSON_UNESCAPED_UNICODE);
                                $spec2->save();
                            }

                            // 三级专业
                            $spec3 = Qh_SchoolSpec::where('name', $_spec['name'])->where('code', $_spec['code'])->where('level', 3)->first();
                            if (!$spec3) {
                                $spec3 = Qh_SchoolSpec::create([
                                    'parentId' => $spec2->id,
                                    'level' => 3,
                                    'name' => $_spec['name'],
                                    'class' => $_spec['class'],
                                    'province' => $provinces,
                                    'code' => $_spec['code'],
                                    'xz' => $_spec['xz']
                                ]);
                            }else {
                                // $s_provinces = json_decode($spec3->province, JSON_UNESCAPED_UNICODE);
                                $s_provinces = is_array($spec3->province) ? $spec3->province : (is_null($spec3->province) ? [] : json_decode($spec3->province, JSON_UNESCAPED_UNICODE));
                                $s_provinces = array_unique(array_merge(json_decode($provinces, JSON_UNESCAPED_UNICODE), $s_provinces));
                                $spec3->province = json_encode(array_values($s_provinces), JSON_UNESCAPED_UNICODE);
                                $spec3->save();
                            }

                            $specIds[] = $spec3->id;
                        }

                        // 将专业和学校关联
                        $specIds = array_merge($specIds, $school->spec()->pluck('schoolSpecId')->toArray());
                        $school->spec()->sync($specIds);

                        // 创建招生计划
                        foreach ($_school['plan'] as $_plan) {
                            $spec = Qh_SchoolSpec::where('name', $_plan['specName'])->where('level', 3)->first();

                            if ($spec) {
                                $_plan['schoolId'] = $school->id;
                                $_plan['schoolSpecId'] = $spec->id;
                                Qh_SchoolPlan::create(Arr::except($_plan, ['specName']));
                            }
                        }
                    }

                    $logs['schoolId'] = $school->id;
                    $logs['schoolName'] = $school->name;

                    DB::commit();
                }catch (Exception $e) {
                    DB::rollBack();
                    Log::debug('【'.$file.'】导入失败：原因：'.$e->getMessage().'(line:)'.$e->getLine());
                    echo '('.($doneCount+1).'/'.$allCount.')【'.$file.'】导入失败：原因：'.$e->getMessage().PHP_EOL;
                    continue;
                }

                echo '('.($doneCount+1).'/'.$allCount.')【'.$file.'】导入完成'.PHP_EOL;
                Log::debug('【'.$file.'】导入完成');
                echo '日志：'.json_encode($logs, JSON_UNESCAPED_UNICODE).PHP_EOL;
                Log::debug('日志：'.json_encode($logs, JSON_UNESCAPED_UNICODE));

                // 删除文件
                unlink($file);

                $doneCount++;
            }
        }

        echo '执行结束，共：'.$allCount.'个，成功导入：'.$doneCount.'个';
        Log::debug('执行结束，共：'.$allCount.'个，成功导入：'.$doneCount.'个');
        return false;
    }
}
